import 'dart:async';
import 'dart:convert';

import 'package:flutter_app1/api/http_constant.dart';
import 'package:flutter_app1/util/app_manager.dart';
import 'package:http/http.dart' as http;

/// API请求
class ApiService {
  // 目标
  static const destination_Url = 'https://sec-m.ctrip.com/restapi/soa2/14422/navigationInfo?_fxpcqlniredt=09031043410934928682';

  /// 网络请求封装，通过方法回调执行的结果(成功或失败)
  static getData(String url, {required Function success, required Function fail, required Function complete}) async {
    try {
      var response = await http.get(Uri.parse(url), headers: HttpConstant.httpHeader);
      if (response.statusCode == 200) {
        var result = json.decode(AppManager.utf8decoder.convert(response.bodyBytes));
        success(result);
      } else {
        throw Exception('"Request failed with status: ${response.statusCode}"');
      }
    } catch (e) {
      fail(e);
    } finally {
      if (complete != null) {
        complete();
      }
    }
  }

  /// 网络请求封装，通过方法回调执行的结果(成功或失败)
  static postData(String url,Object params, {required Function success, required Function fail, required Function complete}) async {
    try {
      var response = await http.post(Uri.parse(url), headers: HttpConstant.httpHeader, body: jsonEncode(params));
      if (response.statusCode == 200) {
        var result = json.decode(AppManager.utf8decoder.convert(response.bodyBytes));
        success(result);
      } else {
        throw Exception('"Request failed with status: ${response.statusCode}"');
      }
    } catch (e) {
      fail(e);
    } finally {
      if (complete != null) {
        complete();
      }
    }
  }
}